package com.hifar.sys;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

public class DataSourceCollect {


    @Value("${spring.datasource.dynamic.datasource.collectdb.url}")
    private String url;

    @Value("${spring.datasource.dynamic.datasource.collectdb.username}")
    private String username;

    @Value("${spring.datasource.dynamic.datasource.collectdb.password}")
    private String password;

    @Value("${spring.datasource.dynamic.datasource.collectdb.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.dynamic.datasource.collectdb.type}")
    private String type;

    @Value("${spring.datasource.dynamic.datasource.collectdb.schema}")
    private String schema;

    private String dbType;

    public String getDbType() {
        if (StringUtils.isNotBlank(url)){
           if (url.startsWith("jdbc:mysql")){
               dbType = "mysql";
           } else if (url.startsWith("jdbc:oracle")){
               dbType = "oracle";
           } else if (url.startsWith("jdbc:sqlserver")){
               dbType = "sqlserver";
           } else if (url.startsWith("jdbc:postgresql")){
               dbType = "postgresql";
           } else if (url.startsWith("jdbc:sqlite")){
               dbType = "sqlite";
           } else if (url.startsWith("jdbc:kingbase8")){
               dbType = "KingBase";
           } else if (url.startsWith("jdbc:dm")){
               dbType = "dm";
           } else if (url.startsWith("jdbc:kingbase")){
               dbType = "kingbase";
           } else if (url.startsWith("jdbc:h2")){
               dbType = "h2";
           } else if (url.startsWith("jdbc:sybase")){
               dbType = "sybase";
           }
        }
        return dbType;
    }

    /**
    * @author heShengJie
    * @Description 获取数据库连接
    * @Date 2024/8/27 11:23
    * @Param []
    * @return java.sql.Connection
    */
    public Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName(driverClassName);
            connection = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }



}
